package ink.tiptop.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author ink.tiptop.zjf
 * @Title: Ticket
 * @Package ink.tiptop.common.validate
 * @Description:
 * @date 2020-07-19 11:13
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] strValues;
    private int[] intValues;
//    private Class<? extends Enum> spec ;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
//        spec = constraintAnnotation.spec();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 枚举类要支持null
        if (value == null) {
            return true;
        }
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (Integer s : intValues) {
                if (s == value) {
                    return true;
                }
            }
        }
        return false;
    }
}
